<template>
  <div class="app-main-content-box">
    <app-main-title title="惠点单报表" />
    <div class="app-main-tips-box top-tips">
      <div class="title"><i class="el-icon-warning" /> 报表说明</div>
      <ul>
        <li>
          1、本表单是商品销售记录，您可以通过筛选数据，得到自己对账或者数据分析所有的数据。
        </li>
      </ul>
    </div>
    <!--filter区域-->
    <div>
      <el-form
        ref="filterForm"
        :model="filterForm"
        label-width="100px"
        size="small"
        :inline="true"
        class="form"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item
              label="选择时间："
              :rules="[{ required: true, message: '时间区间不能为空' }]"
              prop="date"
            >
              <el-date-picker
                v-model="filterForm.date"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="业务单号："
              style="display: inline-block"
              prop="orderNo"
            >
              <el-input
                v-model.trim="filterForm.orderNo"
                placeholder="请输入业务单号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 筛选 -->
        <div class="app-main-filter-collapse-box filter">
          <el-collapse>
            <el-collapse-item ref="filterCollapse" title="按条件筛选" name="1">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="门店：" prop="shopId">
                    <el-select
                      v-model="filterForm.shopId"
                      filterable
                      placeholder="请选择门店"
                    >
                      <el-option
                        v-for="(item, index) in $store.state.user
                          .allManageShopFilterOptions"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-col :span="12">
                    <el-form-item label="商品类型：" prop="productType">
                      <el-select
                        v-model="filterForm.productType"
                        filterable
                        placeholder="请选择商品类型"
                      >
                        <el-option label="全部商品" value="" />
                        <el-option label="主商品" value="MAIN" />
                        <el-option label="赠送商品" value="GIFT" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="商品名称：" prop="productName">
                    <el-input
                      v-model.trim="filterForm.productName"
                      placeholder="请输入商品名称"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-col :span="12">
                    <el-form-item label="订单状态：" prop="status">
                      <el-select
                        v-model="filterForm.status"
                        filterable
                        placeholder="请选择订单状态"
                      >
                        <!-- <el-option label="全部状态" value="" /> -->
                        <el-option :value="3" label="已完成" />
                        <el-option :value="9" label="已退款" />
                        <el-option :value="10" label="待配送" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-col>
                <el-col :span="8">
                  <!-- <el-form-item label="商品分类：" prop="sellclassifyName"> -->
                  <el-form-item label="商品分类：" prop="sellclassifyName">
                    <el-select
                      v-model="filterForm.sellclassifyName"
                      filterable
                      placeholder="请选择商品分类"
                    >
                      <el-option label="全部" value="" />
                      <el-option
                        v-for="(item, index) in classList"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>
                  <!-- </el-form-item> -->
                </el-col>
                <el-col :span="16">
                  <el-col :span="12">
                    <el-form-item label="就餐方式：" prop="orderType">
                      <el-select
                        v-model="filterForm.orderType"
                        filterable
                        placeholder="请选择交易状态"
                      >
                        <el-option label="全部状态" value="" />
                        <el-option :value="1" label="堂食" />
                        <el-option :value="2" label="打包" />
                        <el-option :value="3" label="外卖配送" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="支付方式：" prop="tradeType">
                    <el-radio-group v-model="filterForm.tradeType">
                      <el-radio label="">全部</el-radio>
                      <el-radio
                        v-for="(item, index) in tradeTypeOptions"
                        :key="index"
                        :label="index"
                      >{{ item }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </div>

        <el-form-item class="filter-btn">
          <el-button
            type="primary"
            round
            @click="submitForm('filterForm')"
          >查 询</el-button>
          <el-button round @click="resetForm('filterForm')">重 置</el-button>
          <el-button round @click="downExcel">导 出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 start -->
    <div>
      <AppTableStatisticsCard :statistics-card-data="statisticsCardData" />
    </div>
    <!-- 统计卡片 end -->

    <div>
      <!-- 表格内容 -->
      <div class="list-table">
        <el-table
          size="small"
          :data="list"
          border
          stripe
          style="width: 100%"
          empty-text="暂无数据"
        >
          <el-table-column
            prop="createTime"
            label="下单时间"
            width="135"
            align="center"
          />
          <el-table-column
            prop="orderNo"
            label="业务单号"
            width="160"
            align="center"
          />
          <el-table-column prop="orderType" label="用餐方式" align="center">
            <template slot-scope="scope">
              {{ dinnTypeOptons[scope.row.orderType] }}
            </template>
          </el-table-column>
          <el-table-column prop="productType" label="商品类型" align="center">
            <template slot-scope="scope">
              {{ scope.row.productType === "MAIN" ? "主商品" : "赠送商品" }}
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" align="center">
            <template slot-scope="scope">
              {{ scope.row.productName || "--" }}
            </template>
          </el-table-column>
          <el-table-column prop="classifyName" label="商品分类" align="center">
            <template slot-scope="scope">
              {{ scope.row.classifyName || "--" }}
            </template>
          </el-table-column>
          <el-table-column prop="productSpec" label="商品规格" align="center">
            <template slot-scope="scope">
              {{
                scope.row.productSpecAttr
                  ? scope.row.productSpecAttr.length <= 1
                    ? scope.row.productSpecAttr
                    : scope.row.productSpecAttr.split(",").join("/")
                  : "--"
              }}
            </template>
          </el-table-column>
          <el-table-column label="价格（元）" align="center">
            <template slot-scope="scope">
              {{ ((scope.row.price || 0) / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="num" label="数量" align="center" />
          <el-table-column align="center">
            <template slot="header">
              优惠金额
              <el-tooltip
                class="item"
                effect="light"
                popper-class="el-tooltip-theme-fresh"
                content="优惠金额=原商品价格-销售金额，分摊优惠金额按照占比小的倒推，最后占比高的商品优惠金额=总优惠金额-占比小的优惠金额之和"
                placement="top"
              >
                <i class="el-icon-warning app-text-color-primary" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              {{ ((scope.row.discountAmount || 0) / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="salesPrice" align="center">
            <template slot="header">
              销售金额
              <el-tooltip
                class="item"
                effect="light"
                popper-class="el-tooltip-theme-fresh"
                content="商品按照订单的总商品金额（排除赠送商品、打包费、茶位费）比例计算，分摊销售金额按照占比小的倒推，最后占比高的商品销售金额=总销售金额-占比小的销售金额之和"
                placement="top"
              >
                <i class="el-icon-warning app-text-color-primary" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              {{ ((scope.row.salesPrice || 0) / 100).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" align="center">
            <template slot-scope="scope">
              {{
                scope.row.status === 3
                  ? "已完成"
                  : scope.row.status === 9
                    ? "已退款"
                    : scope.row.status === 10
                      ? "待配送"
                      : "--"
              }}
            </template>
          </el-table-column>
          <el-table-column prop="payStatus" label="交易状态" align="center">
            <template slot-scope="scope">
              {{ payTypeOptions[scope.row.payStatus] || "--" }}
            </template>
          </el-table-column>
          <el-table-column prop="tradeType" label="支付方式" align="center">
            <template slot-scope="scope">
              {{ tradeTypeOptions[scope.row.tradeType] || "--" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="shopName"
            width="180"
            label="门店"
            align="center"
          />
        </el-table>
        <!-- 分页 -->
        <pagination-direction
          v-if="paginationConfig.total !== 0"
          :config="paginationConfig"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { downExportBookingOrders } from '@/api/download'
import {
  queryOrderProducts,
  querySalesNumAndSalesAmount,
  exportCanyinOrderProduct,
  queryClassifyAll
} from '../../bookingModule/api/record'
export default {
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      // 数据
      statisticsCardData: [
        {
          title: '销售数量/个',
          value: 0,
          describeList: ['符合筛选条件的数据中商品销售数量']
        },
        {
          title: '销售金额/元',
          value: 0,
          describeList: ['符合筛选条件的数据中商品销售金额']
        }
      ],
      list: [], // 表格数据
      filterForm: {
        date: [
          `${this.$momentMini().format('YYYY-MM-DD')} 00:00:00`,
          `${this.$momentMini().format('YYYY-MM-DD')} 23:59:59`
        ],
        orderNo: '',
        shopId: '',
        productType: '',
        productName: '',
        orderType: '',
        status: '',
        sellclassifyName: '',
        // payStatus: "",
        tradeType: ''
      },
      tradeTypeOptions: {
        1: '微信支付',
        3: '余额支付'
      },
      payTypeOptions: {
        2: '支付成功',
        4: '已退款'
      },
      dinnTypeOptons: {
        1: '堂食',
        2: '打包',
        3: '外卖配送'
      },
      classList: []
    }
  },
  computed: {
	  ...mapGetters([
		  'userInfo'
	  ])
  },
  mounted() {
    this.fetchData()
    this.queryClassifyAll()
  },
  methods: {
    // 获取列表
    fetchData() {
      this.$refs.filterForm.validate(async(valid) => {
        if (valid) {
          const params = this.getRequirePar()
          queryOrderProducts(params).then((res) => {
            if (res.code === 0) {
              const { pageNum, pageSize, total, list } = res.data
              this.paginationConfig.page = pageNum
              this.paginationConfig.pageSize = pageSize
              this.paginationConfig.total = total
              this.list = list
            }
          })
          querySalesNumAndSalesAmount(params).then((res) => {
            if (res.code === 0) {
              this.statisticsCardData[0].value = res?.data?.salesNum || 0
              this.statisticsCardData[1].value = (
                (res?.data?.salesAmount || 0) / 100
              ).toFixed(2)
            }
          })
        }
      })
    },
    getRequirePar() {
      const {
        paginationConfig: { page, pageSize },
        filterForm
      } = this
      const params = JSON.parse(JSON.stringify(filterForm))
      delete params.date
      if (filterForm.date) {
        params.startTime = filterForm.date[0]
        params.endTime = filterForm.date[1]
      } else {
        params.startTime = ''
        params.endTime = ''
      }
      params.pageNum = page
      params.pageSize = pageSize
	  params.shopId = !this.userInfo.isAdmin && !params.shopId ? this.userInfo.shopId : params.shopId
      return params
    },
    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },
    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    /**
     * 按钮组
     */
    // 导出
    downExcel() {
      const params = this.getRequirePar()
      exportCanyinOrderProduct(params)
        .then((res) => {
          if (res.code === 0) {
            this.$alert('数据导出中，请稍后到数据下载中心进行下载', '提示', {
              confirmButtonText: '确定',
              center: true,
              type: 'success',
              callback: (action) => {}
            })
          }
        })
        .catch((err) => {})
    },

    // 查询
    submitForm() {
      this.paginationConfig.page = 1
      this.paginationConfig.pageSize = 10
      this.fetchData()
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.submitForm()
    },
    queryClassifyAll() {
      queryClassifyAll({}).then((res) => {
        if (res.code == 0) {
          this.classList = res.data
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.top-tips {
  margin-bottom: 20px;
}
.form {
  // background-color: #fff;
  // padding: 20px 30px 0;
  /deep/.el-select,
  .el-date-editor--datetimerange,
  .el-input__inner {
    width: 100% !important;
  }
  .el-form-item {
    width: calc(100% - 20px) !important;
    display: flex !important;
    /deep/.el-form-item__content {
      flex: 1;
    }
  }
}
.to-detail {
  cursor: pointer;
  color: #f0b73d;
}

/deep/.el-tooltip__popper.el-tooltip-theme-fresh {
  border: 1px solid #ffb72f !important;
}
</style>
